package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 石小俊
 * @date 2024年03月27日 19:37
 */
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 获取解析器
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // 进行解析
            List<FileItem> fileItems = upload.parseRequest(request);
            Map<String, FileItem> items = new HashMap<>();
            for (FileItem fileItem : fileItems) {
//                System.out.println(fileItem.getFieldName());
//                if("username".equals(fileItem.getFieldName())){
//                    System.out.println("用户名:"+fileItem.getString());
//                }
//                if("file".equals(fileItem.getFieldName())){
//                    System.out.println("准备上传");
//                }
                items.put(fileItem.getFieldName(), fileItem);
            }
            System.out.println("用户名:" + items.get("username").getString("UTF-8"));

            // 准备上传
            // 上传到服务器中,在服务器根目录中创建一个目录upload,专门存放所有上传的文件
            // 在一个项目中,上传的文件可能会非常多,为了避免混乱,在upload中创建子目录
            // 每天创建一个以当前年月日命名的子目录,用于存放当天上传的文件
            // 想要获取服务器地址,可以通过application对象来获取
            ServletContext application = getServletContext();
            // getRealPath(path):获取服务器地址
            // 参数表示相对与服务器根目录的地址
            // 如果参数为空字符串,表示获取服务器根目录
            // 参数的作用是影响返回值的,其最终返回值为:服务器跟目录+path
            String path = application.getRealPath("/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date()));
            System.out.println(path);
            File f = new File(path);
            // 创建该文件所表示的路径中涉及的所有目录
            f.mkdirs();
            FileItem file = items.get("file");
            String fileName = file.getName();

            // 不允许上传jsp文件
            if (fileName.endsWith(".jsp")) {
                request.setAttribute("uploadMsg", "不允许上传JSP文件");
                request.getRequestDispatcher("/jsp/upload.jsp").forward(request, response);
                return;
            }

            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
            file.write(new File(path, fileName));
            out.print("success");
        } catch (FileUploadException e) {
            e.printStackTrace();
            out.print("fail");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("fail");
        }
    }
}
